﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EasyGrocer.DataLayer;

namespace EasyGrocer.BusinessLayer.ServiceRepository
{
    public class DataContextHttpModule: IHttpModule
    {
        private EasyGrocerDBDataContext _dc;
        public void Init(HttpApplication application)
        {
            if (application.Context.Request.HttpMethod.ToLower() == "get")
            {
                application.EndRequest += new EventHandler(Application_EndRequest);
                application.PostAcquireRequestState += new EventHandler(Application_PostAcquireRequestState);
            }
        }

        void Application_EndRequest(object sender, EventArgs e)
        {
            if(_dc!=null)
            {
                _dc.SubmitChanges();
                //this is to maintain unit of work for asp.net dev server, because it calls get request on css files; iis doesn't have this problem 
                _dc = null;
            }
        }

        void Application_PostAcquireRequestState(object sender, EventArgs e)
        {
            _dc = DataContextContainer.CurrentDataContext;
        }

        public void Dispose()
        {
        }
    }
}
